<template>
    <el-button type="primary" @click="add">添加</el-button>
  <el-table :data="tableData" style="width: 100%">
    <el-table-column label="姓名" width="180" prop="username"/>
    
    <el-table-column label="性别" width="180" prop="sex"/>
    
    <el-table-column label="年龄" width="180" prop="age"/>
    
    <el-table-column label="操作" width="260">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row)">
          编辑
        </el-button>
         <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            :icon="InfoFilled"
            icon-color="#626AEF"
            title="是否删除?"
            @confirm="confirmEvent(scope.row.id)"
            @cancel="cancelEvent"
        >
            <template #reference>
            <el-button type="danger">删 除</el-button>
            </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
</template>

<script  setup>
import axios from 'axios'
import { ref,onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { InfoFilled } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 创建路由实例
const router = useRouter()
//添加调用
const add = () => {
  router.push('/save')
}

const handleEdit = (row) => {
  // 将row转换为json字符串，并打印到控制台
  let jsonstr = JSON.stringify(row)
  console.log(jsonstr);
  
  router.push({
    path: '/save',
    state: {
      user: jsonstr
    }
  })
}
const handleDelete = (index, row) => {
  console.log(index, row)
}
// 创建一个引用，用于存储表格数据
const tableData = ref([])
const show=()=>{
     axios.get('/api/show.do').then(res => {
        tableData.value = res.data
    })
}
//页面加载后执行
onMounted(() => {
   show()
})

//删除
const confirmEvent = (id) => {
  axios.post('/api/delete.do',{id:id,flag:'del'}).then(res => {
        ElMessage({
        message: '删除成功.',
        type: 'success',
    })
    show()
  })
}
const cancelEvent = () => {
  console.log('cancel!')
}
</script>
